package com.hyp.config;

import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.util.ReflectionUtils;

import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import java.lang.reflect.Modifier;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

public class MySpringServletContainerInitializer implements ServletContainerInitializer {

    @Override
    public void onStartup(Set<Class<?>> classes, ServletContext servletContext)
            throws ServletException {


        List<MyWebApplicationInitializer> initializers = new LinkedList<>();

        if (classes != null) {
            for (Class<?> waiClass : classes) {
                // 如果该Class 不是接口，不是抽象类，并且是WebApplicationInitializer类型的类
                if (!waiClass.isInterface() && !Modifier.isAbstract(waiClass.getModifiers()) &&
                        MyWebApplicationInitializer.class.isAssignableFrom(waiClass)) {
                    try {
                        //实例化该类，并加入到initializers集合中
                        initializers.add((MyWebApplicationInitializer)
                                ReflectionUtils.accessibleConstructor(waiClass).newInstance());
                    }
                    catch (Throwable ex) {
                        throw new ServletException("Failed to instantiate WebApplicationInitializer class", ex);
                    }
                }
            }
        }

        if (initializers.isEmpty()) {
            servletContext.log("No Spring WebApplicationInitializer types detected on classpath");
            return;
        }

        servletContext.log(initializers.size() + " Spring WebApplicationInitializers detected on classpath");
        AnnotationAwareOrderComparator.sort(initializers);
        //遍历initializers集合中的类
        for (MyWebApplicationInitializer initializer : initializers) {
            //调用其onStartup方法
            initializer.onStartup(servletContext);
        }

    }


}
